package com.hanhai.material.device.controller;

import com.hanhai.material.common.result.Result;
import com.hanhai.material.common.result.ResultTool;
import com.hanhai.material.device.entity.SysWorkPlan;
import com.hanhai.material.device.service.SysMaterialRecordService;
import com.hanhai.material.device.service.SysWorkPlanService;
import com.hanhai.material.model.workplan.WorkPlan;
import com.hanhai.material.utils.redis.RedisUtil;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.ZoneId;
import java.util.List;

import static com.hanhai.material.device.entity.table.SysWorkPlanTableDef.SYS_WORK_PLAN;
import static com.hanhai.material.utils.TimeUtils.fromDateToString;
import static com.hanhai.material.utils.TimeUtils.getDatesOfMonth;
import static com.mybatisflex.core.query.QueryMethods.distinct;

/**
 * 控制层。
 *
 * @author youchuang
 * @since 2023/10/18 11:26:03
 */
@RestController
@RequestMapping("/work_plan")
@Log4j2
public class SysWorkPlanController {

    @Autowired
    private SysWorkPlanService sysWorkPlanService;


    @Autowired
    private SysMaterialRecordService sysMaterialRecordService;


    @PostMapping("/listByWorkShop/{workShop}")
    public Result<?> listByWorkShop(@PathVariable String workShop) {
        YearMonth yearMonth = YearMonth.now();
        List<LocalDate> dateList = getDatesOfMonth(yearMonth);
        LocalDate start = dateList.get(0);
        LocalDate end = dateList.get(dateList.size() - 1);
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.select(distinct(SYS_WORK_PLAN.MACHINE_NAME.as("name")), SYS_WORK_PLAN.MACHINE_NAME.as("label"));
        queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.likeLeft(workShop));
        queryWrapper.where(SYS_WORK_PLAN.MATERIAL_ID.isNotNull(true));
//        LocalDateTime localDateTime = LocalDateTime.now();
//        LocalDateTime target = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 0, 0, 0);
//        LocalDateTime startTime = target.minusDays(1);
//        LocalDateTime endTime = target.plusDays(1);
//        queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(startTime, endTime));
        queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
        queryWrapper.orderBy(SYS_WORK_PLAN.MACHINE_NAME, true);
        List<WorkPlan> workPlanList = this.sysWorkPlanService.listAs(queryWrapper, WorkPlan.class);
        if (workPlanList.isEmpty()) {
            return ResultTool.fail();
        }
        for (WorkPlan workPlan : workPlanList) {
            queryWrapper = QueryWrapper.create();
            queryWrapper.select(SYS_WORK_PLAN.WORK_PLAN_ID.as("name"), SYS_WORK_PLAN.PRODUCT_NAME.as("label"));
//            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP_ID.eq(workPlan.getId()));
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(workPlan.getName()));
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.eq(workShop));
            queryWrapper.where(SYS_WORK_PLAN.MATERIAL_ID.isNotNull(true));
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));

//            queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(startTime, endTime));
            queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
            queryWrapper.orderBy(SYS_WORK_PLAN.WORK_PLAN_ID, false);
            List<WorkPlan> workPlanList1 = this.sysWorkPlanService.listAs(queryWrapper, WorkPlan.class);
            workPlan.setChildren(workPlanList1);
        }

        return ResultTool.success(workPlanList);
    }

    @Autowired
    RedisUtil redisUtil;


    @PostMapping("/list")
    public Result<?> list(@RequestBody SysWorkPlan sysWorkPlan) {
        log.error("SywWorkPlan:{}", sysWorkPlan);
        YearMonth yearMonth = YearMonth.now();
        List<LocalDate> dateList = getDatesOfMonth(yearMonth);
        LocalDate start = dateList.get(0);
        LocalDate end = dateList.get(dateList.size() - 1);
        QueryWrapper queryWrapper = QueryWrapper.create();
//        queryWrapper.where(SYS_WORK_PLAN.CLOSE_DATE_TIME.isNull());
        if (sysWorkPlan.getWorkShop().equals("成型车间")) {
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(sysWorkPlan.getMachineName()));
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.likeLeft("成型"));
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
//            queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
            if(sysWorkPlan.getExchangeType()!=null&&!sysWorkPlan.getExchangeType().isEmpty()){
                queryWrapper.where(SYS_WORK_PLAN.EXCHANGE_TYPE.eq(sysWorkPlan.getExchangeType()));
                LocalDate localDate=sysWorkPlan.getProductDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                if(localDate.getDayOfMonth()<15){
                    LocalDateTime localDateTime=LocalDate.of(localDate.getYear(),localDate.getMonthValue(),1).atTime(0,0,0);
                    queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(localDateTime,localDate.atTime(0,0,0)).or(SYS_WORK_PLAN.PLAN_END_TIME.between(localDateTime,localDate.atTime(0,0,0))));
                }else{
                    LocalDateTime localDateTime=localDate.minusDays(20).atTime(0,0,0);
                    queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(localDateTime,localDate.atTime(0,0,0)).or(SYS_WORK_PLAN.PLAN_END_TIME.between(localDateTime,localDate.atTime(0,0,0))));
                }
                queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME,false);

            }else{
                queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())).or(SYS_WORK_PLAN.PLAN_END_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate()))));
            }
        } else {
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.eq(sysWorkPlan.getMachineName()));
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
            LocalDateTime localDateTime = LocalDateTime.now();
            LocalDateTime target = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 0, 0, 0);
            LocalDateTime startTime = target.minusDays(1);
            LocalDateTime endTime = target.plusDays(1);
            if(sysWorkPlan.getExchangeType()!=null&&!sysWorkPlan.getExchangeType().isEmpty()){
                queryWrapper.where(SYS_WORK_PLAN.EXCHANGE_TYPE.eq(sysWorkPlan.getExchangeType()));

                queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME,false);
            }else{
                queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())));
            }
            queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
        }
        queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME, true);
        log.error("SQLTOSQL:{}",queryWrapper.toSQL());
        List<SysWorkPlan> sysWorkPlanList = this.sysWorkPlanService.list(queryWrapper);
        return sysWorkPlanList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysWorkPlanList);
    }
    @PostMapping("/list1")
    public Result<?> list1(@RequestBody SysWorkPlan sysWorkPlan) {
        log.error("SywWorkPlan:{}", sysWorkPlan);
        YearMonth yearMonth = YearMonth.now();
        List<LocalDate> dateList = getDatesOfMonth(yearMonth);
        LocalDate start = dateList.get(0);
        LocalDate end = dateList.get(dateList.size() - 1);
        QueryWrapper queryWrapper = QueryWrapper.create();
//        queryWrapper.where(SYS_WORK_PLAN.CLOSE_DATE_TIME.isNull());
        if (sysWorkPlan.getWorkShop().equals("成型车间")) {
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(sysWorkPlan.getMachineName()));
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.likeLeft("成型"));
//            queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
            if(sysWorkPlan.getExchangeType()!=null&&!sysWorkPlan.getExchangeType().isEmpty()){
                queryWrapper.where(SYS_WORK_PLAN.EXCHANGE_TYPE.eq(sysWorkPlan.getExchangeType()));
                queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME,false);
            }else{
                queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())).or(SYS_WORK_PLAN.PLAN_END_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate()))));
            }
        } else {
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.eq(sysWorkPlan.getMachineName()));
            LocalDateTime localDateTime = LocalDateTime.now();
            LocalDateTime target = LocalDateTime.of(localDateTime.getYear(), localDateTime.getMonthValue(), localDateTime.getDayOfMonth(), 0, 0, 0);
            LocalDateTime startTime = target.minusDays(1);
            LocalDateTime endTime = target.plusDays(1);
            if(sysWorkPlan.getExchangeType()!=null&&!sysWorkPlan.getExchangeType().isEmpty()){
                queryWrapper.where(SYS_WORK_PLAN.EXCHANGE_TYPE.eq(sysWorkPlan.getExchangeType()));
                queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME,false);
            }else{
                queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())));
            }
            queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
        }
        queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
        queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME, true);
        log.error("SQLTOSQL:{}",queryWrapper.toSQL());
        List<SysWorkPlan> sysWorkPlanList = this.sysWorkPlanService.list(queryWrapper);
        return sysWorkPlanList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysWorkPlanList);
    }

    @PostMapping("/getSameWorkPlan")
    public Result<?> getSameWorkPlan(@RequestBody SysWorkPlan sysWorkPlan){
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(sysWorkPlan.getPlanStartTime()));
        queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(sysWorkPlan.getMachineName()));
        queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.ne(sysWorkPlan.getWorkPlanId()));
        queryWrapper.limit(1);
        SysWorkPlan workPlan=this.sysWorkPlanService.getOne(queryWrapper);
        return workPlan==null?ResultTool.fail():ResultTool.success(workPlan);
    }

    @PostMapping("/getByWorkPlanId/{workPlanId}")
    public Result<?> getByWorkPlanId(@PathVariable String workPlanId) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanId));
        SysWorkPlan sysWorkPlan = this.sysWorkPlanService.getMapper().selectOneWithRelationsByQuery(queryWrapper);
        log.error("SQL:{}",queryWrapper.toSQL());
        log.error("WorkPlan:{}", sysWorkPlan);
        if (sysWorkPlan == null) {
//            Object object = this.redisUtil.get("websocket");
//            if (object != null) {
//                WebSocketData webSocketData = JSONObject.parseObject(JSONObject.toJSONString(object), WebSocketData.class);
//                webSocketData.setWorkPlan(null);
//                webSocketData.setAllRecordList(new ArrayList<>());
//                webSocketData.setMaterialRecordList(new ArrayList<>());
//                WebSocketServer.sendData(webSocketData);
//                this.redisUtil.set("websocket", webSocketData);
//            }
            ResultTool.fail();
        }
//        Object object = this.redisUtil.get("websocket");
//        if (object != null) {
//            WebSocketData webSocketData = JSONObject.parseObject(JSONObject.toJSONString(object), WebSocketData.class);
//            webSocketData.setWorkPlan(sysWorkPlan);
//            WebSocketServer.sendData(webSocketData);
//            QueryWrapper queryWrapper1 = QueryWrapper.create();
//            queryWrapper1.where(SYS_MATERIAL_RECORD.WORK_PLAN_ID.eq(workPlanId));
////            queryWrapper1.where(SYS_MATERIAL_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd", new Date())));
//            List<SysMaterialRecord> materialRecordList = this.sysMaterialRecordService.list(queryWrapper1);
//            sysWorkPlan.setMaterialRecordList(materialRecordList);
//            webSocketData.setMaterialRecordList(materialRecordList);
//            this.redisUtil.set("websocket", webSocketData);
//        }

        return ResultTool.success(sysWorkPlan);
    }
    @PostMapping("/getByProductId/{productId}")
    public Result<?> getByProductId(@PathVariable String productId) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_WORK_PLAN.PRODUCT_ID.eq(productId));
        queryWrapper.where(SYS_WORK_PLAN.IS_END.eq(false));
//        queryWrapper.orderBy(SYS_WORK_PLAN.)
        queryWrapper.limit(1);
        SysWorkPlan sysWorkPlan = this.sysWorkPlanService.getMapper().selectOneWithRelationsByQuery(queryWrapper);
        log.error("SQL:{}",queryWrapper.toSQL());
        log.error("WorkPlan:{}", sysWorkPlan);
        if (sysWorkPlan == null) {
            ResultTool.fail();
        }
        return ResultTool.success(sysWorkPlan);
    }

    @PostMapping("/reason/list")
    public Result<?> listByReason(@RequestBody SysWorkPlan sysWorkPlan) {
        log.error("SywWorkPlan:{}", sysWorkPlan);
        YearMonth yearMonth = YearMonth.now();
        List<LocalDate> dateList = getDatesOfMonth(yearMonth);
        LocalDate start = dateList.get(0);
        LocalDate end = dateList.get(dateList.size() - 1);
       QueryWrapper queryWrapper = QueryWrapper.create();
        if (sysWorkPlan.getWorkShop().equals("成型车间")) {
            queryWrapper.where(SYS_WORK_PLAN.MATERIAL_ID.isNotNull(true));
            queryWrapper.where(SYS_WORK_PLAN.MACHINE_NAME.eq(sysWorkPlan.getMachineName()));
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.like("成型"));
            queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())));
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));

        } else {
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_ID.isNotNull(true));
            queryWrapper.where(SYS_WORK_PLAN.WORK_SHOP.eq(sysWorkPlan.getMachineName()));
            queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.eq(fromDateToString("yyyy-MM-dd 00:00:00",sysWorkPlan.getProductDate())));
            queryWrapper.where(SYS_WORK_PLAN.PRODUCT_STATUS.eq(1));
        }

        queryWrapper.orderBy(SYS_WORK_PLAN.PLAN_START_TIME,true);
        List<SysWorkPlan> sysWorkPlanList = this.sysWorkPlanService.list(queryWrapper);
        log.error("SQL:{}", queryWrapper.toSQL());

        return sysWorkPlanList.isEmpty() ? ResultTool.fail() : ResultTool.success(sysWorkPlanList);
    }

    @PostMapping("/reason/getByWorkPlanId/{workPlanId}")
    public Result<?> getByWorkPlanIdReason(@PathVariable String workPlanId) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(SYS_WORK_PLAN.WORK_PLAN_ID.eq(workPlanId));
        SysWorkPlan sysWorkPlan = this.sysWorkPlanService.getMapper().selectOneWithRelationsByQuery(queryWrapper);
        log.error("WorkPlan:{}", sysWorkPlan);
        if (sysWorkPlan == null) {
//            Object object = this.redisUtil.get("websocket");
//            if (object != null) {
//                WebSocketData webSocketData = JSONObject.parseObject(JSONObject.toJSONString(object), WebSocketData.class);
//                webSocketData.setWorkPlan(null);
//                webSocketData.setAllRecordList(new ArrayList<>());
//                webSocketData.setMaterialRecordList(new ArrayList<>());
//                WebSocketServer.sendData(webSocketData);
//                this.redisUtil.set("websocket", webSocketData);
//            }
            ResultTool.fail();
        }
//        Object object = this.redisUtil.get("websocket");
//        if (object != null) {
//            WebSocketData webSocketData = JSONObject.parseObject(JSONObject.toJSONString(object), WebSocketData.class);
//            webSocketData.setWorkPlan(sysWorkPlan);
//            WebSocketServer.sendData(webSocketData);
//            QueryWrapper queryWrapper1 = QueryWrapper.create();
//            queryWrapper1.where(SYS_MATERIAL_RECORD.WORK_PLAN_ID.eq(workPlanId));
//            queryWrapper1.where(SYS_MATERIAL_RECORD.PRODUCT_DATE.eq(fromDateToString("yyyy-MM-dd", new Date())));
//            List<SysMaterialRecord> materialRecordList = this.sysMaterialRecordService.list(queryWrapper1);
//            webSocketData.setMaterialRecordList(materialRecordList);
//            this.redisUtil.set("websocket", webSocketData);
//        }
        return ResultTool.success(sysWorkPlan);
    }

    @GetMapping("/getMoldInfoList")
    public Result<?> getMoldInfoList(){
        LocalDateTime endTime=LocalDateTime.now();
        LocalDateTime startTime=endTime.minusDays(30);
        QueryWrapper queryWrapper=QueryWrapper.create();
        queryWrapper.select(distinct(SYS_WORK_PLAN.MOLD_NO));
        queryWrapper.where(SYS_WORK_PLAN.PLAN_START_TIME.between(startTime,endTime));
        List<SysWorkPlan> sysWorkPlanList=this.sysWorkPlanService.list(queryWrapper);
        return  sysWorkPlanList.isEmpty()?ResultTool.fail():ResultTool.success(sysWorkPlanList);
    }
}
